package com.yk.system.controller;

import cn.hutool.core.collection.CollUtil;
import com.yk.api.system.dto.UserDTO;
import com.yk.common.core.domain.LoginUser;
import com.yk.common.core.domain.Result;
import com.yk.common.core.enums.UserStatus;
import com.yk.common.core.exception.user.UserException;
import com.yk.system.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


/**
 * 用户权限 yk-system
 *
 * @author lmx
 * @date 2023/10/16 18:15
 */
@Api(tags = "用户权限")
@RestController
@RequiredArgsConstructor
@RequestMapping("/sys/role")
public class SysRoleController {

    private final RoleService roleService;

    @ApiOperation("通过用户名或手机号查询用户信息")
    @GetMapping("/info")
    public Result<LoginUser> getUserInfo(String username) {
        UserDTO dto = roleService.getUserInfo(username);
        if (Objects.isNull(dto)) {
            throw new UserException("用户不存在");
        }
        if (Objects.isNull(dto.getRoleId())) {
            throw new UserException("无权限登录");
        }
        if (UserStatus.DISABLE.getCode().equals(dto.getStatus())) {
            throw new UserException("用户已停用");
        }
        return Result.data(buildLoginUser(dto));
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(UserDTO user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setPassword(user.getPassword());
        loginUser.setUsername(user.getUserName());
        loginUser.setPhone(user.getPhone());
        loginUser.setNickname(user.getNickName());
        if (Objects.nonNull(user.getRoleId())){
            loginUser.setRolePermission(CollUtil.newArrayList(user.getRoleId().toString()));
        }
        return loginUser;
    }
}
